import 'dart:convert';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/smart_home_water_list_response_bean.dart';
import 'package:e_reception_flutter/ui/common/update_diy_center_info_event.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/create_smart_home_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_simple_store_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_and_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_list_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_index_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/utils/flutter_global_monitoring_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../app_main.dart';
import 'event/refresh_smart_home_index_event.dart';
import 'event/refresh_store_name_event.dart';


class SmartHomeViewModel extends BasePagerViewModel<
    SmartHomeIndexListItemBean,
    SmartHomeIndexResponseBean> {


  ValueNotifier<int> totalValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<CategoryDataBean> categoryValueNotifier;

  ValueNotifier<SmartHomeWaterListDataBean> smartHomeWaterListValueNotifier;

  ValueNotifier<List<SmartHomeStoreAndTerminalListData>> smartHomeStoreAndTerminalListValueNotifier;
  ValueNotifier<List<SimpleStoreListBean>> simpleStoreListValueNotifier;

  SmartHomeViewModel(BaseState<StatefulWidget> state, {CategoryDataBean dataBean})
      : super(state){
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    totalValueNotifier = ValueNotifier(null);
    categoryValueNotifier = ValueNotifier(dataBean??null);
    smartHomeWaterListValueNotifier = ValueNotifier(null);
    smartHomeStoreAndTerminalListValueNotifier = ValueNotifier(null);
    simpleStoreListValueNotifier = ValueNotifier(null);
  }

  ///新增门店详情
  void createStore(BuildContext context, String brand, String name, String logo,
      String province, String city, String district, String address,
      String gps, String code, Function(String id) onCreateSuccess){
    VgHudUtils.show(context, "创建中");
    VgHttpUtils.post(NetApi.ADD_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "brand":brand ?? "",
      "name":name ?? "",
      "logo":logo ?? "",
      "addrProvince":province,
      "addrCity":city,
      "addrDistrict":district,
      "address":address,
      "gps":gps,
      "addrCode":code,
    },callback: BaseCallback(
        onSuccess: (val){
          CreateSmartHomeResponseBean bean =
          CreateSmartHomeResponseBean.fromMap(val);
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new UpdateDiyCenterInfoEvent());
          VgHudUtils.hide(context);
          if(bean != null && StringUtils.isNotEmpty(bean.data)){
            onCreateSuccess.call(bean?.data);
          }else{
            VgToastUtils.toast(AppMain.context, "品牌或门店创建失败，请重试");
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///编辑品牌名
  void editBrandName(BuildContext context, String shid, String brand){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "brand":brand ?? "",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new RefreshStoreNameEvent(brandName: brand));
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///编辑门店名
  void editStoreName(BuildContext context, String shid, String name){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "name":name ?? "",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new RefreshStoreNameEvent(storeName: name));
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///编辑门店logo
  void editStoreLogo(BuildContext context, String shid, String logo){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "logo":logo ?? "",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new RefreshStoreNameEvent(logo: logo));
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///删除门店
  ///删除传01
  void deleteStore(BuildContext context, String shid){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "delflg":"01",
    }, callback: BaseCallback(
        onSuccess: (val){
          String lastShid = UserRepository.getInstance().lastshid;
          if(shid == lastShid){
            UserRepository.getInstance().setLastShid("");
          }
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgHudUtils.hide(context);
          if(StateHelper.has<IndexNavPage>()){
            RouterUtils.popUntil(context, SmartHomeStoreListPage.ROUTER);
          }else{
            RouterUtils.popUntil(context, AppMain.ROUTER);
          }

          VgEventBus.global.send(new UpdateDiyCenterInfoEvent());
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///编辑门店
  ///删除传01
  void editStore(BuildContext context, String shid, String delflg, String name, String logo){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "delflg":delflg ?? null,
      "logo":logo ?? "",
      "name":name ?? "",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new RefreshStoreNameEvent(storeName: name, logo: logo));
          VgHudUtils.hide(context);
          if("01" == delflg){
            RouterUtils.popUntil(context, SmartHomeStoreListPage.ROUTER);
            VgEventBus.global.send(new UpdateDiyCenterInfoEvent());
          }else{
            RouterUtils.pop(context);
          }
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///新增门店图片
  ///style 00现代简约 01中式现代 02美式田园 03美式经典 04欧式豪华 05北欧极简 06日式 07地中海 08潮流混搭 09轻奢 99其他
  ///type 01 图片 02 视频
  void addStorePic(BuildContext context, String backup, String picsize,
      String picstorage, String picurl, String shid, String stid,
      String style, String type, String videopic, String videotime,
      ){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.ADD_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "backup":backup ?? "",
      "picsize":picsize ?? "",
      "picstorage":picstorage ?? "0",
      "picurl":picurl ?? "",
      "shid":shid ?? "",
      "stid":stid ?? "",
      "style":style ?? "",
      "type":type ?? "",
      "videopic":videopic ?? "",
      "videotime":videotime ?? "0",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }


  ///新增分类
  ///type 00新增 01编辑 02删除
  ///stid 智能家居分类id（编辑、删除传）
  void createCategory(BuildContext context, String name, String shid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.ADD_STORE_CATEGORY, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "name":name ?? "",
      "shid":shid ?? "",
      "stid":"",
      "type":"00",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///编辑分类
  ///type 00新增 01编辑 02删除
  ///stid 智能家居分类id（编辑、删除传）
  void editCategory(BuildContext context, String name, String shid, String stid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.ADD_STORE_CATEGORY, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "name":name ?? "",
      "shid":shid ?? "",
      "stid":stid??"",
      "type":"01",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///删除分类
  ///type 00新增 01编辑 02删除
  ///stid 智能家居分类id（编辑、删除传）
  void deleteCategory(BuildContext context, String shid, String stid, int orderflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.ADD_STORE_CATEGORY, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid??"",
      "stid":stid??"",
      "type":"02",
      "orderflg": orderflg??0,
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///获取水印列表
  void getWaterListData(BuildContext context, String shid){
    String cacheKey = NetApi.SMART_HOME_WATER_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + shid;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取水印列表：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        SmartHomeWaterListResponseBean bean = SmartHomeWaterListResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            smartHomeWaterListValueNotifier?.value = bean?.data;
          }
          loading(false);
        }
        getWaterListDataOnLine(shid, cacheKey, bean);
      }else{
        getWaterListDataOnLine(shid, cacheKey, null);
      }
    });
  }

  ///获取水印列表
  void getWaterListDataOnLine(String shid, String cacheKey, SmartHomeWaterListResponseBean bean,) {
    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      "shid": shid,
    };
    VgHttpUtils.post(NetApi.SMART_HOME_WATER_LIST,
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          SmartHomeWaterListResponseBean smartHomeWaterListResponseBean = SmartHomeWaterListResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            if(smartHomeWaterListResponseBean != null && smartHomeWaterListResponseBean.data != null){
              smartHomeWaterListValueNotifier?.value = smartHomeWaterListResponseBean?.data;
            }
          }
          loading(false);
          if(smartHomeWaterListResponseBean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(smartHomeWaterListResponseBean));
            print("缓存文件详情：" + cacheKey + "   " + json.encode(smartHomeWaterListResponseBean));
          }
        }, onError: (e) {
          loading(false);
          VgToastUtils.toast(AppMain.context, e);
          if(bean == null){
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }
        }));
  }

  ///开关水印
  ///水印开关 00开 01关
  void changeWaterStatus(BuildContext context, String shid, String watermark){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "watermark":watermark ?? "00",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///水印样式切换模式
  ///dayflg 00每日更换 01固定一种
  void changeWaterDayFlg(BuildContext context, String shid, String dayflg){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "dayflg":dayflg ?? "00",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///切换水印模板
  void changeWater(BuildContext context, String shid, String wmid){
    if(StringUtils.isEmpty(wmid)){
      return;
    }
    // VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "wmid":wmid,
    }, callback: BaseCallback(
        onSuccess: (val){
          String cacheKey = NetApi.SMART_HOME_WATER_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
              + shid;
          ///获取缓存数据
          Future<String> future = SharePreferenceUtil.getString(cacheKey);
          future.then((jsonStr){
            if(!StringUtils.isEmpty(jsonStr)){
              Map map = json.decode(jsonStr);
              SmartHomeWaterListResponseBean bean = SmartHomeWaterListResponseBean.fromMap(map);
              if(bean != null){
                bean.data.wmid = wmid;
                SharePreferenceUtil.putString(cacheKey, json.encode(bean));
              }
            }
          });
          VgHudUtils.hide(context);
          // RouterUtils.pop(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///文件播放模式切换
  ///type 00动态模式 01静态模式
  void changeMediaPlayModule(BuildContext context, String shid, String type){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "type":type ?? "00",
    }, callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///编辑地址信息
  void editAddressInfo(BuildContext context, String shid, String province, String city,
      String district, String address, String gps, String code){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_SMART_HOME_STORE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "addrProvince":province,
      "addrCity":city,
      "addrDistrict":district,
      "address":address,
      "gps":gps,
      "addrCode":code,
    }, callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          RouterUtils.pop(context);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///获取门店和设备列表
  void getStoreAndTerminalList(String shid, String gps, String searchName){
    VgHttpUtils.get(NetApi.SMART_HOME_STORE_AND_TERMINAL_LIST, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "gps":gps ?? "",
      "searchName":searchName ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeStoreAndTerminalResponseBean bean =
          SmartHomeStoreAndTerminalResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null && bean.data.list != null){
              smartHomeStoreAndTerminalListValueNotifier?.value = bean?.data?.list;
              if(bean.data.list != null && bean.data.list.isNotEmpty){
                statusTypeValueNotifier?.value = null;
              }else{
                statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
              }
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///获取门店简约列表
  void getSimpleStoreList(String searchName){
    VgHttpUtils.get(NetApi.SMART_HOME_SIMPLE_STORE_LIST, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "searchName":searchName ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeSimpleStoreListResponseBean bean =
          SmartHomeSimpleStoreListResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null && bean.data.list != null){
              simpleStoreListValueNotifier?.value = bean?.data?.list;
              if(bean.data.list != null && bean.data.list.isNotEmpty){
                statusTypeValueNotifier?.value = null;
              }else{
                statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
              }
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }



  @override
  void onDisposed() {
    totalValueNotifier?.dispose();
    statusTypeValueNotifier?.dispose();
    smartHomeWaterListValueNotifier?.dispose();
    super.onDisposed();
  }


  @override
  bool isNeedCache() {
    return true;
  }


  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "current": page ?? 1,
      "size": 20,
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return NetApi.GET_SMART_HOME_LIST;
  }

  @override
  SmartHomeIndexResponseBean parseData(VgHttpResponse resp) {
    SmartHomeIndexResponseBean vo = SmartHomeIndexResponseBean.fromMap(resp?.data);
    FlutterGlobalMonitoringUtils?.dataNotifier?.value = vo?.code;
    loading(false);
    if((vo?.data?.page?.total??0) > 0){
      statusTypeValueNotifier?.value = null;
    }else{
      statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
    }
    totalValueNotifier.value = vo?.data?.page?.total;
    print("_storeCount:" + totalValueNotifier.value.toString());
    SharePreferenceUtil.putInt(SP_STORE_COUNT, totalValueNotifier.value);
    return vo;
  }

  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  Stream<String> get onRefreshFailed => Stream.value(null);
}
